package com.exp.practice.workbench.service.teacher.impl;

import com.exp.practice.base.exception.MyException;
import com.exp.practice.workbench.dao.ExaminationQuestionRelationDao;
import com.exp.practice.workbench.dao.QuestionDao;
import com.exp.practice.workbench.domain.Question;
import com.exp.practice.workbench.service.teacher.TeacherPracticeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TeacherPracticeServiceImpl implements TeacherPracticeService {

    @Resource
    private QuestionDao questionDao;

    @Resource
    private ExaminationQuestionRelationDao examinationQuestionRelationDao;

    @Override
    public int addQuestion(Question question) throws MyException {
        int count=questionDao.addQuestion(question);
        if(count!=1){
            throw new MyException("添加题目失败");
        }
        return count;
    }

    @Override
    public int getTotal(Question question) {
        int total=questionDao.getTotal(question);
        return total;
    }

    @Override
    public List<Question> getQuestions(String pageNo, String pageSize, Question question) {
        int pageNos=Integer.valueOf(pageNo);
        int pageSizes=Integer.valueOf(pageSize);
        //记录略过的记录条数
        int skipCount=(pageNos-1)*pageSizes;
        String createTime = question.getCreateTime();
        String head = question.getHead();
        List<Question> list=questionDao.getQuestionList(skipCount,pageSizes,createTime,head);
        return list;
    }

    @Override
    public List<Question> getQuestionById(String qid) {
        List<Question> list=questionDao.getQuestionById(qid);
        return list;
    }

    @Override
    public int update(Question question) throws MyException {
        int count=questionDao.update(question);
        if (count!=1){
            throw new MyException("修改题目失败");
        }
        return count;
    }

    @Override
    public int delete(String[] qid) throws MyException {
        String []ids=examinationQuestionRelationDao.isExists(qid);
        //所选题目中有已组卷题目
        String msg="";
        if(ids.length!=0){
            for (int i = 0; i < ids.length; i++) {
                msg+=ids[i];
                if(i< ids.length-1){
                    msg+=",";
                }
            }
            throw new MyException("题目编号为"+msg+"的题目已组卷，不能删除");
        }
        /*for (String id:qid){
            int count=examinationQuestionRelationDao.isExists(id);
            if(count>0){//存在
                throw new MyException("编号为"+id+"的题目已组卷，不能删除");
            }
        }*/
        int count2=questionDao.delete(qid);
        if(count2!=qid.length){
          throw new MyException("删除失败");
        }
        return count2;
    }
}
